import React, { Component } from 'react'

import From from './Form'
import List from './List'

import './style.css'

export default class TodoList extends Component {
    constructor(props) {
        super(props);
        this.state = {
            list: [
                {
                    id: 0,
                    title: '看书',
                    isComplete: false
                }
            ]
        }
    }
    add = (title) => {
        let data = {
            id: this.state.list.length,
            title,
            isComplete: false
        }
        let newList = [...this.state.list];
        newList.unshift(data);
        this.setState({
            list: newList
        })
    }
    changeItem = (item) => {
        let newList = [...this.state.list]
        let index = newList.findIndex(i => i.id === item.id)
        item.isComplete = !item.isComplete
        newList[index] = item
        this.setState({
            list: newList
        })
    }
    del = (item) => {
        let newList = [...this.state.list]
        let index = newList.findIndex(i => i.id === item.id)
        newList.splice(index, 1)
        this.setState({
            list: newList
        })
    }
    render() {
        const { list } = this.state
        return (
            <div className='todolist'>
                <h2>TodoList</h2>
                <From 
                    add={this.add}
                />
                <List 
                    changeItem={this.changeItem} 
                    list={list} 
                    del={this.del}
                />
            </div>
        )
    }
}
